<?php

if ($_SERVER["REQUEST_URI"] == "/" && $_SERVER["REQUEST_METHOD"] == "GET") {
    echo <<<INDEX_HTML
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/" method="POST">
<span>请输入长URL：</span><input type="text" name="url"></input><br>
<input type="submit"></input>
</form>
</body>
</html>
INDEX_HTML;
} elseif ($_SERVER["REQUEST_URI"] == "/" && $_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["url"])) {
        echo <<<HTML_EMPTY_URL
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="5; url=/">
</head>
<body>
<p>URL不能为空</p>
</body>
</html>
HTML_EMPTY_URL;
    } else {
        $hashResultBinrary = hash("crc32", $_POST["url"], true);
        $fileName = bin2hex($hashResultBinrary);
        if (!is_dir("data")) {
            mkdir("data");
        }
        file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . "data" . DIRECTORY_SEPARATOR . "$fileName.txt", $_POST["url"]);
        $url = urlencode(base64_encode($hashResultBinrary));
        $urlHtmlDisplay = htmlspecialchars($url);
        $ref = "";
        if (!empty($_SERVER["HTTP_REFERER"])) {
            $ref = rtrim($_SERVER["HTTP_REFERER"], "/");
        }
        echo <<<HTML_SHORT_URL
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>生成的短网址是：  <a href="/$url">$ref/$urlHtmlDisplay</a></p>
</body>
</html>
HTML_SHORT_URL;
    }
} else {
    $urlArray = explode("?", ltrim($_SERVER["REQUEST_URI"], "/"));
    $shortUrlWithBase64 = urldecode($urlArray[0]);
    $hashResultBinrary = base64_decode($shortUrlWithBase64);
    $fileName = bin2hex($hashResultBinrary);
    if (!is_file(__DIR__ . DIRECTORY_SEPARATOR . "data" . DIRECTORY_SEPARATOR . "$fileName.txt")) {
        echo <<<HTML_ERR_URL
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>不存在映射关系文件，地址错误。</p>
</body>
</html>
HTML_ERR_URL;
    } else {
        $url = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . "data" . DIRECTORY_SEPARATOR . "$fileName.txt");
        http_response_code(301);
        header("Location: $url");
    }
}



